/**
 * Created by PanJiaChen on 16/11/18.
 */
import Vue from 'vue';
import moment from 'moment';
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}
// 非空判断
export function empty(v) {
  if (v === 0) {
    return true
  }
  if (!v) {
    return false
  }
  return true
}
//去除annotationList对象字符串后边的逗号
function setItems(data) {
  let newArr = []
  data.forEach((str) => {
    str =
      str.substring(str.length - 1) == ","
        ? str.substring(0, str.length - 1)
        : str;
    newArr.push(str)
  });
  return newArr;
  // str=(str.substring(str.length-1)==',')?str.substring(0,str.length-1):str
}
//第一级添加标识
function setArrOne(arr) {
  let newArr = JSON.parse(JSON.stringify(arr))
  newArr.forEach(item => {
    item.level = 1
  })
  return newArr
}
//封装自定义注释字符串
export function parseTreeJson(arr) {
  arr = setArrOne(arr)
  let treeStr = ''
  function treeJson(arr) {
    arr.forEach(function (item, index) {
      if (item.children && item.children.length) {
        treeStr += ('@' + item.label + '(')
        treeJson(item.children);
      } else {
        if (item.isKey) {
          treeStr += (`'${item.label}'='${item.value}'`)
        } else {
          treeStr += ('@' + item.label + '(')
        }
      }
      if (arr.length === index + 1) {
        let isKeyStr = item.isKey ? '' : ')'
        treeStr += isKeyStr
      } else {
        let isKeyStr = item.isKey ? ',' : '),'
        treeStr += isKeyStr
      }
      //判断是不是第一级 加?后边字符串转数组用
      if (item.level === 1) {
        treeStr += '?'
      }
      // @xxxx(@x-1001xxx(keyxx='valuexx',?key='value',?@x-1004(key='value',?key='value',?@x-1007()))),?@xx(
    })
    // treeStr += '?'
  }
  treeJson(arr)
  // return arr
  let newStr = treeStr.split('?')
  const newArr = setItems(newStr) //去除末尾逗号
  // treeStr = ''
  console.log(treeStr, 'treeStr')
  return newArr
}
//排序
export function treeSort(arr) {
  arr = JSON.parse(JSON.stringify(arr))
  toParse(arr)
  function toParse(arr) {
    arr.forEach(function (item) {
      if (item.children.length !== 0) {
        item.children.sort((a, b) => b.isKey - a.isKey)
        toParse(item.children)
      }
    })
  }
  return arr
}
//验证键值对
export function verificationTree(arr) {
  let iskey = true
  let iskeyArr = []
  let noKeyAnnotation = []
  arr = setArrOne(arr)
  iskey && toParse(arr)
  function toParse(arr) {
    arr.forEach(function (item) {
      const children = item.children; //自己是否包含键值
      if (item.level === 1 && children.length == 0) {
        iskey = false
        iskeyArr.push(iskey)
        if (!iskey) {
          noKeyAnnotation.push(item)
        }
      } else if (!item.isKey) {
        iskey = children.some((chil) => {
          return chil.isKey == true
        })
        // if (!iskey) {
        //   noKeyAnnotation.push(item)
        // }
        // iskeyArr.push(iskey)
      }
      if (item.children.length !== 0) {

        if (item.level === 1) {
          for (let i = 0; i < item.children.length; i++) {
            const childrenI = item.children[i]; //子注释是否包含键值
            //自己不包含键值,查子注释是否包含
            if (children.length !== 0 && !iskey) {
              iskey = childrenI.children.some((chil) => {
                return chil.isKey == true
              })
              if (!iskey) {
                noKeyAnnotation.push(childrenI)
              }
              iskeyArr.push(iskey)
            }
          }
        } else {
          // for (let i = 0; i < item.children.length; i++) {
          const children = item.children;
          //判断数组中是否有 keyvalue iskey说明有 返回true
          iskey = children.some((chil) => {
            return chil.isKey == true
          })
          if (!iskey && !item.isKey) {
            noKeyAnnotation.push(item)
          }
          iskeyArr.push(iskey)
          // }
        }
        toParse(item.children);
      } else {
        if (!item.isKey) {
          iskey = false
          iskeyArr.push(iskey)
          if (!iskey) {
            noKeyAnnotation.push(item)
          }
        }
      }
    })
  }

  return unique(noKeyAnnotation, 'id')
}
//整个树形结构的节点是否都包含key
function isKeyValue(arr) {
  return arr.every(item => {
    return item === true
  })
}
//修改最后提交的 annotationListObjects 对象
export function parseJson(arr, newKey = 'annotations', oldKey = 'children') {
  arr = arr.slice()
  function toParse(arr) {
    arr.forEach(function (item) {
      item.elements = []
      item[newKey] = []
      if (item[oldKey] && Array.isArray(item[oldKey])) {
        for (let i = 0; i < item[oldKey].length; i++) {
          const element = item[oldKey][i];
          if (element.isKey) {
            element = {
              key: element.label, //key
              value: element.value, //value
            }
            item.elements.push(element)
          } else {
            item[newKey].push(element)
          }
        }
        item.name = item.label
        toParse(item[newKey])
      }
      // delete item.children
    })
    return arr
  }
  return toParse(arr)
}
//反编译annotationListObjects 的树形结构回显
export function reverseJson(arr2, name = 'Async') {
  let arr = JSON.parse(JSON.stringify(arr2))
  if (Array.isArray(name)) {
    arr = arr.filter(item => !name.includes(item.name))
  } else {
    const arrIndex = arr.findIndex(item => item.name == name)
    if (arrIndex != -1) {
      arr.splice(arrIndex, 1)
    }
  }
  function toParse(arr) {
    arr.forEach(function (item) {
      item.id = generateId()
      item.children = []
      if (item.annotations && Array.isArray(item.annotations) || item.elements && Array.isArray(item.elements)) {
        for (let i = 0; i < item.annotations.length; i++) {
          let element = item.annotations[i];
          element.isKey = false
          element.id = generateId() //随机id 不然删除会出现错乱问题
          item.children.push(element)

        }
        for (let i = 0; i < item.elements.length; i++) {
          let element = item.elements[i];
          element = {
            id: generateId(),
            label: element.key,
            value: element.value,
            isKey: true,
            ...element
          }
          item.children.push(element)
        }
        item.label = item.name
        toParse(item.children)
      }
    })
    return arr
  }
  // 如果提交的格式 在获取的时候 不会乱 也可以不走treeSort排序
  const resArr = treeSort(toParse(arr))
  return resArr
}
//随机id
export function generateId(num = 32) {
  var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
  var maxPos = chars.length;
  var pwd = "";
  for (var i = 0; i < num; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;

}
export function uuid(len = 16, radix = 16) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [],
    i;
  radix = radix || chars.length;

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}
function unique(arr, key) {
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {

    for (var j = i + 1; j < arr.length; j++) {

      if (arr[i][key] == arr[j][key]) {
        ++i;
      }
    }
    newArr.push(arr[i]);
  }
  return newArr;
}

export const delay = (function () {
  let timer = 0;
  return function (callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();
export function regTextName(name, msg = '名称首位必须为字母且不能包含特殊符号和空格,请检查!') {
  var reg = /^[a-zA-Z][-_a-zA-Z0-9]{0,5}/;
  if (!reg.test(name)) {
    // Vue.prototype.$msg(msg)
    return false;
  } else {
    return true
  }
}
// 获取当前视口的高度
export function getClientHeight(height = 150) {
  // height 其他内容的高度 默认 150
  var h =
    document.documentElement.clientHeight || document.body.clientHeight;
  return h - height;
}
// 数字补0
export const pad = (num, cover = 2) => "0".repeat(cover).concat(num).slice(-cover);
// 生成合炉的 规则token
export const useFurnaceToken = (form, index, type) => {
  return `${moment().format("YYYYMMDD")}-${form.partNumber}-${form.batchNumber
    }-${form.processNumber}-${type}-${pad(index)}`;
}
export const useAccountToken = (form) => {
  return `${moment().format("YYYYMMDD")}-${form.partNumber}-${form.batchNumber
    }-${form.processNumber}`;
}